#!/usr/bin/python

import datetime, sys, subprocess

suffix = ['java', 'txt', 'css', 'js', 'xml', 'properties', 'py', 'groovy', 'jsp', 'vm', 'ftl', 'MF', 'tld', '']


def validate_author_date(commit):
    p = subprocess.Popen(['git show --pretty=format:%at', commit],
        shell=True, stdout=subprocess.PIPE)
    x = p.stdout.readline()
    if x.strip():
        ad = datetime.date.fromtimestamp(int(x))
        #print 'author time:%s' % str(ad)
        #print 'sys time:%s' % str(datetime.date.today())
        return ad <= datetime.date.today()
    else:
        return False

def validate_line_ending(base, commit):
    p = subprocess.Popen(['git', 'diff', '--numstat', '%s..%s' %(base, commit)], stdout=subprocess.PIPE, shell=True)
    files = p.communicate()[0].split('\n')
    for f in files:
        if is_text_file(f):
            temp_file = open(f, 'rb')
            if temp_file.read().find('\r\n'):
                temp_file.close()
                return False
            temp_file.close()
    return True

def is_text_file(fname):
    seg = fname.split('.')
    return len(seg) > 1 and seg[-1] in suffix

for line in sys.stdin:
    (base, commit, ref) = line.strip().split()
    #print base, commit, ref
    if not validate_author_date(commit):
        sys.exit('Date error, commit date is ahead of server date')
    elif not validate_line_ending(base, commit):
        sys.exit('Line ending error, windows style line ending found in commit')
    else:
        sys.exit(0)

